﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Build.Construction;

namespace Genuilder
{
	public class MSBuildData
	{
		public MSBuildData(Project project)
		{
			_Project = project;
		}
		private readonly Project _Project;
		public Project Project
		{
			get
			{
				return _Project;
			}
		}
		private IEnumerable<ProjectElement> EnumerateNextChildren(ProjectElement element)
		{
			element = element.NextSibling;
			while(element != null)
			{
				var next = element.NextSibling;
				yield return element;
				element = next;
			}
		}
		ProjectImportElement _StartImportGenuilder;
		public ProjectImportElement StartImportGenuilder
		{
			get
			{
				EnsureParse();
				return _StartImportGenuilder;
			}
		}
		ProjectImportElement _EndImportGenuilder;
		public ProjectImportElement EndImportGenuilder
		{
			get
			{
				EnsureParse();
				return _EndImportGenuilder;
			}
		}

		ProjectRootElement _ProjectRootElement;

		public ProjectRootElement ProjectRootElement
		{
			get
			{
				EnsureParse();
				return _ProjectRootElement;
			}
		}
		private ProjectImportElement FindImport(string import)
		{
			return ProjectRootElement.Imports.FirstOrDefault(i => i.Project == import);
		}

		private void EnsureParse()
		{
			if(_ProjectRootElement == null)
			{
				_ProjectRootElement = ProjectRootElement.Open(_Project.Path);
				_StartImportGenuilder = FindImport("StartGenuilder");
				_EndImportGenuilder = FindImport("EndImportGenuilder");
				if(_StartImportGenuilder != null)
				{
					UnInstallFeatures();
				}

				if(_StartImportGenuilder == null)
				{
					_StartImportGenuilder = ProjectRootElement.AddImport("StartGenuilder");
					_StartImportGenuilder.Condition = "'Genuilder internal dont touch  or apocalypse will come' == 'true'";
				}

				if(_EndImportGenuilder == null)
				{
					_EndImportGenuilder = ProjectRootElement.AddImport("EndGenuilder").After(StartImportGenuilder);
					_EndImportGenuilder.Condition = "'Genuilder internal dont touch or apocalypse will come' == 'true'";
				}
				_ProjectRootElement
					.AddPropertyGroup()
					.After(_StartImportGenuilder)
					.AddProperty("UseHostCompilerIfAvailable", "false");
			}
		}

		internal void UnInstallFeatures()
		{
			foreach(var element in EnumerateNextChildren(StartImportGenuilder))
			{
				if(element == EndImportGenuilder)
					break;
				element.Parent.RemoveChild(element);
			}
		}
	}
}
